package com.nerve.android.cloudoffice.app.activity.im;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.util.DateUtil;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.worker.MessageLoadListener;
import com.nerve.android.cloudoffice.app.worker.MessageLoadManager;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.domain.Message;
import com.nerve.android.cloudoffice.service.data.MessageData;

/**
 * @project: Cloudoffice_android
 * @file: MessageViewActivity.java
 * @package: com.nerve.android.cloudoffice.app.activity.im
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 22, 2013
 * @change log:
 */
@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_message_view)
public class MessageViewActivity extends NavigationActivity
			implements OnClickListener, MessageLoadListener{
	
	public final static String NAME = "name";
	public final static String ID = "id";
	
	private int targetId;
	private String targetname;
	
	@ViewOnId(id=R.id.view_list)
	private ListView listView;
	@ViewOnId(id=R.id.view_input)
	private EditText inputET;
	@ViewOnId(id=R.id.view_send, clickListener="this")
	private Button sendBTN;
	
	private List<Message> list = new ArrayList<Message>();
	private ViewAdapter adapter;
	private Message message;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			sendBTN.setEnabled(true);
			
			switch (msg.what) {
			case WORKER_OK:
				MessageData.saveMessageToDB(message);
				break;
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		super.initUI();
		
		if(targetId == 0){
			toast("参数错误！");
			finish();
		}
		
		setNavTitle(targetname);
		
		adapter = new ViewAdapter();
		this.listView.setAdapter(adapter);
		
		MessageLoadManager.addListener(this);
	}
	
	@Override
	protected void initData() {
		targetname = getIntent().getStringExtra(NAME);
		targetId = getIntent().getIntExtra(ID, 0);
		
		
		List<Message> tempL = MessageData.getMessageRecord(OfficeApplication.getLoginId(), targetId);
		if(tempL != null)
			list = tempL;
		
		for(Message m:list){
			Const.log("----->"+m);
		}
	}
	
	/**
	 * 当返回键被点击时
	 */
	@Override
	protected void onNavigateBackButtonClick() {
		setResult(RESULT_CANCELED, null);
		finish();
	}

	@Override
	public void onMessageLoaded(int size) {
		Const.log("MessageViewActivity==============onMessageLoadDone: size=" + size);
		if(size > 0){
			/*
			List<Message> tempL = MessageData.getLastedMessage(targetId);
			
			if(tempL.size() == 0)
				return ;
				
			for(Message m:tempL)
				list.add(m);
			*/
			
			List<Message> tempL = MessageData.getMessageRecord(OfficeApplication.getLoginId(), targetId);
			
			if(tempL != null){
				list = tempL;
				adapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public String getLoaderName() {
		return "message_view";
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.view_send){
			if(isEmpty(inputET)){
				toast("请输入发送内容");
				return ;
			}
			
			sendBTN.setEnabled(false);
			
			addMessageToList();
			inputET.setText("");
			
			new MessageWorker().execute();
		}
	}
	
	/**
	 * @method name: addMessageToList
	 * @description: 增加到列表中
	 * @return type: void
	 *
	 */
	private void addMessageToList(){
		message = null;
		message = new Message();
		message.setFromId(OfficeApplication.getLoginId());
		message.setFromUser(OfficeApplication.USER.getName());
		message.setToId(targetId);
		message.setToUser(targetname);
		message.setMessage(inputET.getText().toString());
		message.setGroupId(targetId);
		message.setJoinDate(new Date());
		message.setRead(true);
		
		list.add(message);
		adapter.notifyDataSetChanged();
		
		Const.log("发送消息：" + message.toString());
	}
	
	private class MessageWorker extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			Reply re = MessageData.sendMessage(
					OfficeApplication.getLoginId(), 
					targetId, 
					message.getMessage()
					);
			
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			return WORKER_OK;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
		
	}
	
	private class ViewAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View v, ViewGroup arg2) {
			Message m = (Message)getItem(arg0);
			
			v = View.inflate(
					MessageViewActivity.this, 
					m.getFromId() == targetId?
							R.layout.activity_message_view_listitem2 
							:
							R.layout.activity_message_view_listitem, 
					null
					);
			
			((TextView)v.findViewById(R.id.content)).setText(m.getMessage());
			((TextView)v.findViewById(R.id.date)).setText(
						DateUtil.toString(m.getJoinDate())
					);
			return v;
		}
		
	}
}